
package com.jy.framework.sys.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jy.framework.sys.entity.SysDeptEntity;
import com.jy.framework.utils.Constant;
import com.jy.framework.sys.controller.AbstractController;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.jy.framework.annotation.SysLog;
import com.jy.framework.exception.MyException;
import com.jy.framework.utils.R;
import com.jy.framework.sys.entity.SysMenuEntity;
import com.jy.framework.sys.service.SysMenuService;

/**
 * 系统菜单
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年10月27日 下午9:58:15
 */
@Api(tags = "系统菜单")
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends AbstractController {
    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 导航菜单
     */
    @RequestMapping("/nav")
    public R nav() {
        List<SysMenuEntity> menuList = sysMenuService.getUserMenuList(getUserId());
        return R.ok().put("menuList", menuList);
    }

    /**
     * 所有菜单列表
     */
    @GetMapping("/list")
    @RequiresPermissions("sys:menu:list")
    public List<SysMenuEntity> list(@Param("keyword") String keyword) {
        QueryWrapper<SysMenuEntity> menuEntityQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(keyword)) {
            menuEntityQueryWrapper.lambda().and(q->q.like(SysMenuEntity::getUrl, keyword).or().like(SysMenuEntity::getName, keyword));
        }
        List<SysMenuEntity> menuList = sysMenuService.list(menuEntityQueryWrapper);
        fillParentName(menuList);
        return menuList;
    }

    private void fillParentName(List<SysMenuEntity> menuList) {
        Map<Long, SysMenuEntity> menuEntityMap = menuList.stream().collect(Collectors.toMap(key -> key.getId(), value -> value));
        for (SysMenuEntity sysMenuEntity : menuList) {
            SysMenuEntity parentDeptEntity = menuEntityMap.get(sysMenuEntity.getParentId());
            if (parentDeptEntity != null) {
                sysMenuEntity.setParentName(parentDeptEntity.getName());
            }
        }
    }

    /**
     * 选择菜单(添加、修改菜单)
     */
    @RequestMapping("/select")
    @RequiresPermissions("sys:menu:select")
    public R select() {
        //查询列表数据
        List<SysMenuEntity> menuList = sysMenuService.queryNotButtonList();

        //添加顶级菜单
        SysMenuEntity root = new SysMenuEntity();
        root.setId(0L);
        root.setName("一级菜单");
        root.setParentId(-1L);
        root.setOpen(true);
        menuList.add(root);

        return R.ok().put("menuList", menuList);
    }

    /**
     * 菜单信息
     */
    @RequestMapping("/info/{menuId}")
    @RequiresPermissions("sys:menu:info")
    public R info(@PathVariable("menuId") Long menuId) {
        SysMenuEntity menu = sysMenuService.getById(menuId);
        return R.ok().put("menu", menu);
    }

    /**
     * 保存
     */
    @SysLog("保存菜单")
    @PostMapping("/save")
    @RequiresPermissions("sys:menu:save")
    public R save(@RequestBody SysMenuEntity menu) {
        //数据校验
        verifyForm(menu);

        sysMenuService.save(menu);

        return R.ok();
    }

    /**
     * 修改
     */
    @SysLog("修改菜单")
    @RequestMapping("/update")
    @RequiresPermissions("sys:menu:update")
    public R update(@RequestBody SysMenuEntity menu) {
        //数据校验
        verifyForm(menu);

        sysMenuService.updateById(menu);

        return R.ok();
    }

    /**
     * 删除
     */
    @SysLog("删除菜单")
    @RequestMapping("/delete")
    @RequiresPermissions("sys:menu:delete")
    public R delete(long menuId) {
        if (menuId <= 31) {
            return R.error("系统菜单，不能删除");
        }

        //判断是否有子菜单或按钮
        List<SysMenuEntity> menuList = sysMenuService.queryListParentId(menuId);
        if (menuList.size() > 0) {
            menuList.stream().forEach(m -> {

                Long id = m.getId();
                sysMenuService.delete(id);

                List<SysMenuEntity> sysMenuEntities = sysMenuService.queryListParentId(id);
                if (sysMenuEntities.size() > 0) {
                    sysMenuEntities.stream().forEach(m1 -> {

                        Long id1 = m1.getId();
                        List<SysMenuEntity> menuEntities = sysMenuService.queryListParentId(id1);
                        menuEntities.stream().forEach(a -> {
                            sysMenuService.delete(a.getId());
                        });
                        sysMenuService.delete(id1);

                    });
                }
            });
        }

        sysMenuService.delete(menuId);

        return R.ok();
    }

    /**
     * 验证参数是否正确
     */
    private void verifyForm(SysMenuEntity menu) {
        if (StringUtils.isBlank(menu.getName())) {
            throw new MyException("菜单名称不能为空");
        }

        if (menu.getParentId() == null) {
            throw new MyException("上级菜单不能为空");
        }

        //菜单
        if (menu.getType() == Constant.MenuType.MENU.getValue()) {
            if (StringUtils.isBlank(menu.getUrl())) {
                throw new MyException("菜单URL不能为空");
            }
        }

        //上级菜单类型
        int parentType = Constant.MenuType.CATALOG.getValue();
        if (menu.getParentId() != 0) {
            SysMenuEntity parentMenu = sysMenuService.getById(menu.getParentId());
            parentType = parentMenu.getType();
        }

        //目录、菜单
        if (menu.getType() == Constant.MenuType.CATALOG.getValue() ||
                menu.getType() == Constant.MenuType.MENU.getValue()) {
            if (parentType != Constant.MenuType.CATALOG.getValue()) {
                throw new MyException("上级菜单只能为目录类型");
            }
            return;
        }

        //按钮
        if (menu.getType() == Constant.MenuType.BUTTON.getValue()) {
            if (parentType != Constant.MenuType.MENU.getValue()) {
                throw new MyException("上级菜单只能为菜单类型");
            }
            return;
        }
    }

    /**
     * 批量删除
     */
    @RequestMapping("/batchDel")
    @ResponseBody
    public R batchDel(@RequestBody long[] ids) {
        sysMenuService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }
}
